package com.zzg.Filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zzg.bean.Manage;

/**
 * 判断用户是否登陆的过滤器
 */
//@WebFilter("/*")
public class LoginFilter implements Filter{
	
	//不拦截的链接
	private static final String[] EXCLUSIVE_URL={"login.jsp","login.do","code.do",".png",".jpg",".js",".css",".ttf"};
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		//转换后才能调用getSession
		HttpServletRequest request = (HttpServletRequest) req;
		//转换后才能调用重定向
		HttpServletResponse response =(HttpServletResponse) resp;
		Manage manage = (Manage) request.getSession().getAttribute("Manage");
		
		//若是遇到不拦截的url则直接放行
		for(String str:EXCLUSIVE_URL){
			if(request.getRequestURI().toString().endsWith(str)){
				chain.doFilter(req, resp);
				return;
			}
		}
		
		//管理员若为空则进行拦截(强制跳转到登陆页面)
		if(manage == null){
			System.out.println("拦截了:"+request.getRequestURI());
			response.sendRedirect("login.jsp");
		}else{
			System.out.println("放行，"+request.getRequestURI());
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {
		
	}
	
}
